<template>
    <view>
        <view v-if="cartsList.length===0" class="null">当前购物车为空</view>
        <view v-else class="card">
            <view class="header">
                <!-- 修改为 checkbox-group -->
                <checkbox-group @change="toggleAllCheck">
                    <checkbox :checked="isAllChecked" />全选
                </checkbox-group>
                <view></view>
                <button @click="clearCart">清空购物车</button>
            </view>
            <view class="body" v-for="(item, index) in cartsList" :key="item.id">
                <!-- 修改为 checkbox-group -->
                <checkbox-group @change="(e) => toggleCheck(index, e)">
                    <checkbox :checked="item.checked" />
                </checkbox-group>
                <image :src="item.img" style="width:50px;height:50px;"/>
                <view class="product-info">
                    <view class="name">{{ item.name }}</view>
                    <view class="sales">月售{{ item.sales }}件</view>
                    <view class="price">
                        <view class="new_old">
                            <view class="new">￥{{ item.price }}</view>
                            <view class="old">￥{{ item.oldPrice }}</view>
                        </view>
                        <view class="sum">
                            <button @click="dele(index)">-</button>
                            <view style="margin:5px;">{{item.quantity }}</view>
                            <button @click="add(index)">+</button>
                        </view>
                    </view>
                </view>
            </view>
            <view class="foot">
                <view class="total">总计：<text>￥{{num}}</text></view>
                <button @click="checkout" class="button">去结算({{selectedCount}})</button>
            </view>
        </view>
    </view>
</template>
<script>
import config from '../config.js';
import axios from 'axios';
export default {
    data() {
        return {
            cartsList: [],
        }
    },
    onShow() {
        this.numcarts()
    },
    methods: {
        numcarts() {
            uni.request({
                url:config.api_host+ "/carts",
                success: (res) => {
                    this.cartsList = res.data.map(item => ({
                        ...item,
                        checked: false
                    }))
                }
            })
        },
        add(index) {
            this.cartsList[index].quantity++
        },
        dele(index) {
            if (this.cartsList[index].quantity > 1) {
                this.cartsList[index].quantity--;
            } else if (this.cartsList[index].quantity === 1) {
                this.cartsList.splice(index, 1)
            }
        },
        clearCart() {
            axios.get(config.api_host+"/carts")
              .then(res => {
                    const items = res.data;
                    const deletePromises = items.map(item => {
                        return axios.delete(config.api_host+`/carts/${item.id}`)
                    });
                    return Promise.all(deletePromises);
                })
              .then(() => {
                    this.cartsList = []; // 清空本地数据
                    uni.showToast({
                        title: '清除成功',
                    })
                })
              .catch(err => {
                    console.error('清空购物车失败:', err);
                    uni.showToast({
                        title: '清除失败',
                        icon: 'none'
                    })
                });
        },
        checkout() {
            const selectedItems = this.cartsList.filter(item => item.checked);
            if (selectedItems.length === 0) {
                uni.showToast({
                    title: '请选择要结算的商品',
                    icon: 'none'
                });
                return;
            }
            uni.navigateTo({
                url: `/pages/dingdan/suredingdan?selectedItems=${JSON.stringify(selectedItems)}`
            });
        },
        toggleCheck(index, e) {
            // 获取当前checkbox的选中状态
            const isChecked = e.detail.value.length > 0;
            // 使用Vue.set确保响应式更新
            this.$set(this.cartsList[index], 'checked', isChecked);
        },
        toggleAllCheck(e) {
            // 获取全选checkbox的选中状态
            const isChecked = e.detail.value.length > 0;
            // 创建新数组确保响应式更新
            this.cartsList = this.cartsList.map(item => ({
                ...item,
                checked: isChecked
            }));
        },
    },
    computed: {
        num() {
            return this.cartsList
               .filter(item => item.checked)
               .reduce((total, item) => {
                    return total + item.price * item.quantity;
                }, 0)
               .toFixed(2);
        },
        isAllChecked() {
            return this.cartsList.length > 0 && this.cartsList.every(item => item.checked);
        },
        selectedCount() {
            return this.cartsList.filter(item => item.checked).length;
        }
    },
}
</script>
<style scoped>
.total {
    color: red;
}

.null {
    text-align: center;
    padding: 20px;
}

.card {
    padding: 10px;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #e9e7e7;
}

.body {
    display: flex;
    align-items: center;
    padding: 10px;
    border-bottom: 1px solid #e9e7e7;
}

.product-info {
    margin-left: 10px;
}

.name {
    font-size: 16px;
}

.sales {
    font-size: 14px;
    color: gray;
}

.price {
    display: flex;
    align-items: center;
}

.new_old {
    display: flex;
    align-items: center;
}

.new {
    font-size: 18px;
    color: red;
    margin-right: 10px;
}

.old {
    font-size: 16px;
    color: gray;
    text-decoration: line-through;
}

.sum {
    display: flex;
    align-items: center;
}

.foot {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
}

.button {
    background-color: rgb(93, 93, 138);
    color: white;
}
</style>